<template>
	<view class="flex flex-row">
		<slot name="default" :data="{ data: time_data, finish: isfinish }">
			<text :style="{color:color,fontSize:fontSize }">{{text}}</text>
		</slot>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				timid: undefined,
				now: 0,
				isfinish: true,
			}
		},
		props: {
			fontSize: {
				type: Number,
				default: 28,
			},
			time: {
				type: Number,
				default: 10 * 1000,
			},
			format: {
				type: String,
				default: "DD天HH小时MM分SS秒MS毫秒",
			},
			autoStart: {
				type: Boolean,
				default: true,
			},
			color: {
				type: String,
				default: "",
			},
		},
		computed: {
			time_data() {
				return this.formatTime(this.time - this.now)
			},
			text() {
				let ps = this.format;
				ps = ps.replace(/(DD)/g, String(this.time_data.day));
				ps = ps.replace(/(MM)/g, String(this.time_data.minutes));
				ps = ps.replace(/(HH)/g, String(this.time_data.hour));
				ps = ps.replace(/(SS)/g, String(this.time_data.seconds));
				ps = ps.replace(/(MS)/g, String(this.time_data.millisecond));
				return ps;
			}
		},
		watch: {
			now(newVal) {
				if (newVal == this.time || newVal == 0) {
					this.isfinish = true
				}
			}
		},
		onMounted() {
			this.formatTime(this.time);
			if (this.autoStart) {
				this.start()
			}
		},
		methods: {
			formatTime(my_time) {
				var daysRound = Math.floor(my_time / 1000 / 60 / 60 / 24);
				var hoursRound = Math.floor((my_time / 1000 / 60 / 60) % 24);
				var minutesRound = Math.floor((my_time / 1000 / 60) % 60);
				var secondsRound = Math.floor((my_time / 1000) % 60);
				var millisecondRound = Math.floor(my_time % 1000);
				let time = {
					day: daysRound > 9 ? daysRound : "0" + daysRound, //天
					hour: hoursRound > 9 ? hoursRound : "0" + hoursRound, //小时,
					minutes: minutesRound > 9 ? minutesRound : "0" + minutesRound, //分.
					seconds: secondsRound > 9 ? secondsRound : "0" + secondsRound, //秒。
					millisecond: millisecondRound > 9 ? millisecondRound : "00" + millisecondRound, //毫秒。
				};
				return time;
			},
			// 开始或者继续。
			start() {
				clearInterval(this.timid);
				this.$emit("start");
				this.timid = setInterval(() => {
					let lst = this.now + 50;
					if (lst > this.time) {
						clearInterval(this.timid);
						this.isfinish = true;
						this.$emit("end");
						return;
					}
					this.isfinish = false;
					this.now = lst;
					this.$emit("change", this.time_data);
				}, 50);
			},
			// 停止，直接结束。
			stop() {
				clearInterval(this.timid);
				this.now = this.time;
				this.$emit("end");
			},
			// 暂停。
			pause() {
				clearInterval(this.timid);
			},
			// 重置。
			resinit() {
				clearInterval(this.timid);
				this.now = 0;
				this.isfinish = true;
			}
		}
	}
</script>